<?php
namespace app\__MODULE__\controller;
use app\__MODULE__\model\{Order as OrderModel,StoreOrderStatus};
use think\facade\Db;

class Order extends  Base{

	/**
	 * 订单列表
	 * @return [type] [description]
	 */
	public  function index(){
		$search  = request()->param();
        if(IS_POST) {
            $db   = OrderModel::search_model($search)->append(['status_name']);
            $list = $db->limit(paginator())->select();
            __MODULE___response(0, 'success', $list, $db->count());
        }
        $count = OrderModel::count(); //全部订单
        $count0 = OrderModel::where('paid', 0)->where('status', 0)->where('refund_status', 0)->count();//未支付
        $count1 = OrderModel::where('paid', 1)->where('status', 0)->where('refund_status', 0)->count();// 待发货
        $count2 = OrderModel::where('paid', 1)->where('status', 1)->where('refund_status', 0)->count();//待收货
        $count3 =OrderModel::where('paid', 1)->where('status', 2)->where('refund_status', 0)->count();//已完成
        $count4 = OrderModel::where('paid', 1)->where('refund_status', 1)->count(); //申请退款
        $count5 = OrderModel::where('paid', 1)->where('refund_status', 2)->count(); //申请退款通过
        $count6 = OrderModel::where('paid', 1)->where('refund_status', 3)->count(); //申请退款拒绝
        $this->assign(compact('count','count0','count1','count2','count3','count4','count5','count6'));
        return $this->fetch();
    }

    /**
     * 订单详情
     * @return [type] [description]
     */
    public function detail(){
        $id = param_check('id');
        if (!$id || !($orderInfo = OrderModel::with('user')->get($id)))
            json_response(0,'订单不存在!');
        $this->assign(compact('orderInfo'));
        return $this->fetch();
    }

    /**
     * 订单日志记录
     * @return [type] [description]
     */
    public function order_log(){
        $id      = param_check('id');
        $search  = request()->param();
        if(IS_POST) {
            $db   = StoreOrderStatus::where('oid',$id)->order('change_time desc');
            $list = $db->limit(paginator())->select();
            __MODULE___response(0, 'success', $list, $db->count());
        }

        return $this->render_table([
            "cols" => [ 
                    ["field"=>"change_message", "title"=>"操作记录","align"=>"center"],
                    ["field"=>"change_time", "title"=>"操作时间","align"=>"center"],
                    ["field"=>"ip", "title"=>"操作IP","align"=>"center"],
                    ["field"=>"change_name", "title"=>"操作人","align"=>"center"]

            ],
            ],false);
    }

    /**
     * 修改订单
     * @return [type] [description]
     */
    public function edit(){
        $id = \param_check('id');
        if(request()->isPost()) {
            $data = request()->post();
            try{
                OrderModel::update($data,['id'=>$id]);
                StoreOrderStatus::setStatus($id, 'order_edit', '修改商品总价为：' . $data['total_price'] . ' 实际支付金额' . $data['pay_price'].'收货地址为'.$data['user_address']);
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                json_response(0,$e->getMessage());  
            }
            json_response(1,'操作成功');  
         
         }else{
            $data   = OrderModel::find($id);
            $option = [
                ['title'=>'顺丰快递','value'=>'SF'],
                ['title'=>'中通快递','value'=>'ZTO'],
                ['title'=>'EMS','value'=>'EMS'],
                ['title'=>'中国邮政','value'=>'YZ'],
                ['title'=>'圆通快递','value'=>'YT']
            ];
            return $this->render_form([
                ['type'=>'text', 'name'=>'order_id', 'title'=>'订单号', 'lay-verify'=>'required','disabled'=>true],
                ['type'=>'text','text_type'=>'number' ,'name'=>'total_price', 'title'=>'订单总价'],
                ['type'=>'text', 'text_type'=>'number','name'=>'pay_price', 'title'=>'支付价格'],
                ['type'=>'text', 'name'=>'user_address', 'title'=>'收货地址']
            ],$data);
         }
    }
    /**
     * 物流信息
     * @return [type] [description]
     */
    public function distribution(){
        $id = \param_check('id');
        if(request()->isPost()) {
            $data = request()->post();
            try{
                OrderModel::update($data,['id'=>$id]);
                StoreOrderStatus::setStatus($id, 'distribution', '修改发货信息为' . $data['delivery_name'] . '号' . $data['delivery_id'],$this->mg_user['username']);
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                json_response(0,$e->getMessage());  
            }
            json_response(1,'操作成功');  
         
         }else{
            $data   = OrderModel::find($id);
            $option = [
                ['title'=>'顺丰快递','value'=>'SF'],
                ['title'=>'中通快递','value'=>'ZTO'],
                ['title'=>'EMS','value'=>'EMS'],
                ['title'=>'中国邮政','value'=>'YZ'],
                ['title'=>'圆通快递','value'=>'YT']
            ];
            return $this->render_form([
                ['type'=>'text', 'name'=>'order_id', 'title'=>'订单号', 'lay-verify'=>'required'],
                ['type'=>'select', 'name'=>'delivery_name', 'title'=>'快递公司','option'=>$option,'lay-search'=>'true'],
                ['type'=>'text', 'name'=>'delivery_id', 'title'=>'快递单号', 'lay-verify'=>'required']
            ],$data);
         }
    }

    /**
     * 发货
     * @return [type] [description]
     */
    public function deliver(){
        $id = \param_check('id');
        if(request()->isPost()) {
            $data = request()->post();
            try{
                $data['status'] = 1;
                OrderModel::update($data,['id'=>$id]);
                StoreOrderStatus::setStatus($id, 'delivery_goods', '已发货 快递公司：' . $data['delivery_name'] . ' 快递单号：' . $data['delivery_id']);
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                json_response(0,$e->getMessage());  
            }
            json_response(1,'操作成功');  
         
         }else{
            $data   = OrderModel::find($id);
            $option = [
                ['title'=>'顺丰快递','value'=>'SF'],
                ['title'=>'中通快递','value'=>'ZTO'],
                ['title'=>'EMS','value'=>'EMS'],
                ['title'=>'中国邮政','value'=>'YZ'],
                ['title'=>'圆通快递','value'=>'YT']
            ];
            return $this->render_form([
                ['type'=>'text', 'name'=>'order_id', 'title'=>'订单号', 'lay-verify'=>'required','readonly'=>true],
                ['type'=>'select', 'name'=>'delivery_name', 'title'=>'快递公司','option'=>$option,'lay-search'=>'true'],
                ['type'=>'text', 'name'=>'delivery_id', 'title'=>'快递单号', 'lay-verify'=>'required']
            ],$data);
         }
    }

    /**
     * 退款审核通过
     * @return [type] [description]
     */
    public function  refund_y(){
        $id = \param_check('id');
        if(request()->isPost()) {
            $data = request()->post();
            try{
                $product = OrderModel::find($id);
                if (!$product) exception('数据不存在!');
                if (!$data['pay_price']) exception('请输入退款金额');
                $data['refund_price']   = $data['pay_price'];
                if($product->refund_status !=1) exception('订单状态异常');
                $bj = bccomp((float)$product['pay_price'], (float)$data['refund_price'], 2);
                if ($bj < 0) exception('退款金额大于支付金额，请修改退款金额');
                if ($data['type'] == 1) {
                    $data['refund_status'] = 2;
                } else if ($data['type'] == 2) {
                    //退回原状态
                    $data['refund_status'] = 0;
                }
                $service = new \app\common\api\WeChat;
                $refund_order_sn = 'TK'.time(); //退款单号  自行生成
                $res = $service->doRefund($product->pay_price,$data['refund_price'],$refund_order_sn,$product->transaction_id);
                $data['refund_sn']   = $refund_order_sn;
                OrderModel::update($data,['id'=>$id]);
                StoreOrderStatus::setStatus($id, 'refund_price', '退款给用户' . $data['refund_price'] . '元');
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                json_response(0,$e->getMessage());  
            }
            json_response(1,'操作成功');  
         
         }else{
            $data   = OrderModel::find($id);
            $option = [
                ['title'=>'直接退款','value'=>'1'],
                ['title'=>'退款后,返回原状态','value'=>'2']
            ];
            return $this->render_form([
                ['type'=>'text', 'name'=>'order_id', 'title'=>'订单号', 'lay-verify'=>'required','readonly'=>true],
                 ['type'=>'text','text_type'=>'number', 'name'=>'pay_price', 'title'=>'退款金额','lay-verify'=>'required'],
                ['type'=>'radio', 'name'=>'type', 'title'=>'退款金额','option'=>$option],
            ],$data);
         }
    }
	
    /**
     * 退款拒绝
     * @return [type] [description]
     */
    public function  refund_n(){
        $id = \param_check('id');
        if(request()->isPost()) {
            $data = request()->post();
            try{
                $product = OrderModel::find($id);
                if (!$product) exception('数据不存在!');
               if (!$data['refund_reason']) exception('请输入退款原因');
                $data['refund_status'] = 3;
                OrderModel::update($data,['id'=>$id]);
                StoreOrderStatus::setStatus($id, 'refund_n', '不退款原因:' . $data['refund_reason']);
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                json_response(0,$e->getMessage());  
            }
            json_response(1,'操作成功');  
         
         }else{
            $data   = OrderModel::find($id);
            return $this->render_form([
                ['type'=>'text', 'name'=>'order_id', 'title'=>'订单号', 'lay-verify'=>'required','readonly'=>true],
                 ['type'=>'textarea', 'name'=>'refund_reason', 'title'=>'拒绝原因','lay-verify'=>'required']
            ],$data);
         }
    }
}